import { IsArray, ObjectCopy, ObjectKeys } from '.'

export const HttpCode = {
  200: '成功',
  300: '功能',
  301: '下载文件功能',
  400: '无处理方法',
  500: '错误处理'
}
// 空 或 0 或 '0' 为顶级tree
const isPid = pid => !pid || pid === '0'

const ArrayReduce = (data, reduce, init) => {
  const list = init || []
  if (IsArray(data)) return data.reduce(reduce, list)
  return list
}

export const searchWord = (keyword, data, key) => {
  if (!keyword || !key) return data
  const reduce = (arr, { children, ...item }) => {
    let isPush = false
    String(item[key])
      .toLowerCase()
      .includes(String(keyword).toLowerCase()) && (isPush = true)
    const child = searchWord(keyword, children, key)
    child.length && (isPush = true)
    if (isPush) {
      const nd = ObjectCopy(item)
      child.length && (nd.children = child)
      arr.push(nd)
    }
    return arr
  }
  return ArrayReduce(data, reduce)
}

export const handleData = (data, config, option) => {
  const [raw, std] = config || []
  const { all } = option || {}
  const reduce = (list, item) => {
    const res = {}
    if (IsArray(raw)) {
      all &&
        ObjectKeys(item || {}).forEach(
          key => raw.includes(key) || (res[key] = item[key])
        )
      raw.forEach((key, i) => {
        if (IsArray(std)) {
          const skey = std[i]
          const val = item[key]

          if (val || val === 0 || val === false) {
            if (IsArray(val)) {
              if (val.length) {
                const nd = handleData(val, config, option)
                res[skey] ? res[skey].push(...nd) : (res[skey] = nd)
              }
            } else {
              res[skey] = val
            }
          }
        }
      })
    }
    return list.push(res), list
  }
  return ArrayReduce(data, reduce)
}

export const normalData = data =>
  data.map(item => {
    const { label, value } = item || {}
    return { label, value }
  })

export const normalTree = data => {
  const map = {}
  const tree = []
  const reduce = (list, item) => {
    const { id, pid, ...child } = item
    child.id = id
    if (isPid(pid)) list.push(child)
    map[id] = child
    return list
  }
  data.reduce(reduce, tree)
  const each = item => {
    const { id, pid } = item || {}
    const child = map[pid]
    if (child) {
      const { children } = child
      children
        ? map[pid].children.push(map[id])
        : (map[pid].children = [map[id]])
    }
  }
  data.forEach(each)
  return tree
}

export const normalMap = data => {
  const reduce = (obj, item) => {
    const { value, label, children } = item || {}
    obj[value] = label
    return ArrayReduce(children, reduce, obj)
  }
  return ArrayReduce(data, reduce, {})
}
export const toListData = (data, map) => {
  if (IsArray(data)) return data.map(map)
  return []
}

export const toTreeData = (data, reduce) =>
  normalTree(ArrayReduce(data, reduce))

export const toMapData = (data, reduce) => ArrayReduce(data, reduce, {})
